package com.example.lncd.ui.elderly;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.lncd.R;
import com.example.lncd.api.ApiService;
import com.example.lncd.api.RetrofitClient;
import com.example.lncd.model.Location;
import com.example.lncd.model.User;
import com.example.lncd.model.LocationRequest;
import com.example.lncd.ui.auth.LoginActivity;
import com.example.lncd.util.Constants;
import com.example.lncd.util.PreferenceManager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.MapView;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ElderlyMainActivity extends AppCompatActivity implements TencentLocationListener {

    private Toolbar toolbar;
    private MapView mapView;
    private TextView tvLocationStatus;
    private RecyclerView recyclerView;
    private Button btnAddRelation, btnEmergencyContact;
    private FloatingActionButton fabSOS;
    
    private TencentMap tencentMap;
    private TencentLocationManager locationManager;
    private TencentLocationRequest locationRequest;
    
    private ApiService apiService;
    private PreferenceManager preferenceManager;
    private RelatedFamilyAdapter adapter;
    
    private List<User> relatedFamilies = new ArrayList<>();
    private Long currentUserId;
    private boolean isLocationServiceRunning = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_elderly_main);
        
        // 初始化组件
        initViews();
        
        // 初始化地图
        initMap(savedInstanceState);
        
        // 初始化API和用户信息
        initApiAndUserInfo();
        
        // 请求位置权限
        requestLocationPermission();
        
        // 加载关联家人
        loadRelatedFamilies();
        
        // 设置按钮点击事件
        setButtonListeners();
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        
        // 处理Toolbar - 在使用setSupportActionBar前先检查主题中是否已有ActionBar
        try {
            setSupportActionBar(toolbar);
        } catch (IllegalStateException e) {
            // 如果已经有ActionBar，则直接设置标题
            toolbar.setTitle("关爱端");
            setSupportActionBar(null); // 确保使用系统ActionBar
        }
        
        mapView = findViewById(R.id.mapView);
        tvLocationStatus = findViewById(R.id.tvLocationStatus);
        recyclerView = findViewById(R.id.recyclerRelatedFamilies);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        
        btnAddRelation = findViewById(R.id.btnAddRelation);
        btnEmergencyContact = findViewById(R.id.btnEmergencyContact);
        fabSOS = findViewById(R.id.fabSOS);
    }
    
    private void initMap(Bundle savedInstanceState) {
        // 按照腾讯地图SDK文档初始化地图
        if (mapView != null) {
            try {
                // 尝试获取地图实例
                tencentMap = mapView.getMap();
                if (tencentMap != null) {
                    tencentMap.setMapType(TencentMap.MAP_TYPE_NORMAL);
                    
                    // 设置初始位置为中国中心点
                    LatLng centerOfChina = new LatLng(35.86166, 104.195397);
                    tencentMap.moveCamera(CameraUpdateFactory.newLatLngZoom(centerOfChina, 4));
                    
                    // 设置地图加载完成回调
                    tencentMap.setOnMapLoadedCallback(() -> {
                        Toast.makeText(ElderlyMainActivity.this, "地图加载完成", Toast.LENGTH_SHORT).show();
                    });
                    
                    Toast.makeText(this, "地图初始化成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "地图实例获取失败", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                // 捕获任何地图初始化时的异常
                Toast.makeText(this, "地图初始化异常: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        } else {
            Toast.makeText(this, "地图视图对象为空", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void initApiAndUserInfo() {
        apiService = RetrofitClient.getApiService();
        preferenceManager = new PreferenceManager(this);
        
        currentUserId = preferenceManager.getUserId();
        
        // 设置RecyclerView适配器
        adapter = new RelatedFamilyAdapter(relatedFamilies);
        recyclerView.setAdapter(adapter);
    }
    
    private void requestLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    Constants.REQUEST_LOCATION_PERMISSION);
        } else {
            initLocationService();
        }
    }
    
    private void initLocationService() {
        // 检查GPS是否开启
        LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        
        if (!gpsEnabled) {
            showGpsDisabledAlert();
            return;
        }
        
        // 初始化定位服务
        locationManager = TencentLocationManager.getInstance(this);
        locationRequest = TencentLocationRequest.create();
        locationRequest.setInterval(Constants.LOCATION_UPDATE_INTERVAL);
        locationRequest.setRequestLevel(TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA);
        
        // 启动定位服务
        int error = locationManager.requestLocationUpdates(locationRequest, this);
        if (error == 0) {
            isLocationServiceRunning = true;
            tvLocationStatus.setText("位置状态: 已开启");
        } else {
            tvLocationStatus.setText("位置状态: 启动失败");
        }
    }
    
    private void showGpsDisabledAlert() {
        new AlertDialog.Builder(this)
                .setTitle("定位服务未开启")
                .setMessage("请开启GPS定位服务")
                .setPositiveButton("设置", (dialog, which) -> {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    private void loadRelatedFamilies() {
        if (currentUserId == -1) {
            Toast.makeText(this, "用户信息错误，请重新登录", Toast.LENGTH_SHORT).show();
            return;
        }
        
        Call<List<User>> call = apiService.getRelatedUsers(currentUserId);
        call.enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    relatedFamilies.clear();
                    relatedFamilies.addAll(response.body());
                    adapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(ElderlyMainActivity.this, "获取关联家人失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<List<User>> call, Throwable t) {
                Toast.makeText(ElderlyMainActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void setButtonListeners() {
        fabSOS.setOnClickListener(v -> {
            showSOSDialog();
        });
        
        btnAddRelation.setOnClickListener(v -> {
            showAddRelationDialog();
        });
        
        btnEmergencyContact.setOnClickListener(v -> {
            showEmergencyContactDialog();
        });
    }
    
    private void showSOSDialog() {
        new AlertDialog.Builder(this)
                .setTitle("紧急求助")
                .setMessage("是否向您的家人发送紧急求助信息？")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 发送SOS消息逻辑
                    Toast.makeText(ElderlyMainActivity.this, "已发送紧急求助信息", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    private void showAddRelationDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_relation, null);
        EditText etUsername = dialogView.findViewById(R.id.etUsername);
        
        new AlertDialog.Builder(this)
                .setTitle("添加关联")
                .setView(dialogView)
                .setPositiveButton("添加", (dialog, which) -> {
                    String username = etUsername.getText().toString().trim();
                    if (!username.isEmpty()) {
                        // 先查询用户ID
                        Call<List<User>> usersCall = apiService.getAllUsers();
                        usersCall.enqueue(new Callback<List<User>>() {
                            @Override
                            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                                if (response.isSuccessful() && response.body() != null) {
                                    List<User> allUsers = response.body();
                                    // 查找匹配用户名的用户
                                    for (User user : allUsers) {
                                        if (user.getUsername().equals(username)) {
                                            // 找到用户，添加关联
                                            addRelation(user.getId());
                                            return;
                                        }
                                    }
                                    Toast.makeText(ElderlyMainActivity.this, "未找到该用户名的用户", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(ElderlyMainActivity.this, "获取用户列表失败", Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onFailure(Call<List<User>> call, Throwable t) {
                                Toast.makeText(ElderlyMainActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    private void addRelation(Long relatedUserId) {
        // 调用添加关联API
        Call<User> call = apiService.relateUser(currentUserId, relatedUserId);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(ElderlyMainActivity.this, "添加关联成功", Toast.LENGTH_SHORT).show();
                    // 刷新关联用户列表
                    loadRelatedFamilies();
                } else {
                    Toast.makeText(ElderlyMainActivity.this, "添加关联失败: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Toast.makeText(ElderlyMainActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void showEmergencyContactDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_emergency_contact, null);
        EditText etPhone = dialogView.findViewById(R.id.etPhone);
        
        // 先获取当前用户信息
        Call<User> call = apiService.getUserById(currentUserId);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful() && response.body() != null) {
                    User user = response.body();
                    if (user.getEmergencyContact() != null) {
                        etPhone.setText(user.getEmergencyContact());
                    }
                    
                    new AlertDialog.Builder(ElderlyMainActivity.this)
                            .setTitle("设置紧急联系人")
                            .setView(dialogView)
                            .setPositiveButton("保存", (dialog, which) -> {
                                String phone = etPhone.getText().toString().trim();
                                if (!phone.isEmpty()) {
                                    user.setEmergencyContact(phone);
                                    updateUserEmergencyContact(user);
                                }
                            })
                            .setNegativeButton("取消", null)
                            .show();
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Toast.makeText(ElderlyMainActivity.this, "获取用户信息失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void updateUserEmergencyContact(User user) {
        Call<User> call = apiService.updateUser(user.getId(), user);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(ElderlyMainActivity.this, "紧急联系人设置成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(ElderlyMainActivity.this, "紧急联系人设置失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Toast.makeText(ElderlyMainActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    @Override
    public void onLocationChanged(TencentLocation location, int error, String reason) {
        if (error == TencentLocation.ERROR_OK) {
            // 定位成功
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            
            // 检查地图是否初始化
            if (tencentMap != null) {
                // 在地图上显示当前位置
                LatLng latLng = new LatLng(latitude, longitude);
                tencentMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
                
                // 清除之前的标记
                tencentMap.clearAllOverlays();
                
                // 添加新标记
                MarkerOptions markerOptions = new MarkerOptions()
                        .position(latLng)
                        .title("当前位置");
                tencentMap.addMarker(markerOptions);
            } else {
                Toast.makeText(this, "地图未初始化，无法显示位置", Toast.LENGTH_SHORT).show();
            }
            
            // 上传位置到服务器
            uploadLocation(latitude, longitude, location.getAddress());
        } else {
            // 定位失败
            Toast.makeText(this, "定位失败：" + reason, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onStatusUpdate(String name, int status, String desc) {
        // 位置状态更新，可以根据需要处理
    }
    
    private void uploadLocation(double latitude, double longitude, String address) {
        try {
            // 使用新的LocationRequest类
            LocationRequest locationRequest = new LocationRequest(
                currentUserId, 
                latitude, 
                longitude, 
                address
            );
            
            // 上传位置
            Call<Location> call = apiService.addSimpleLocation(locationRequest);
            call.enqueue(new Callback<Location>() {
                @Override
                public void onResponse(Call<Location> call, Response<Location> response) {
                    if (response.isSuccessful()) {
                        // 上传成功
                    } else {
                        Toast.makeText(ElderlyMainActivity.this, 
                            "位置上传失败: " + response.code(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<Location> call, Throwable t) {
                    Toast.makeText(ElderlyMainActivity.this, 
                        "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception e) {
            Toast.makeText(this, "位置上传错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Constants.REQUEST_LOCATION_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initLocationService();
            } else {
                Toast.makeText(this, "需要位置权限才能提供服务", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_elderly_main, menu);
        
        // 确保菜单项文字显示正确
        for (int i = 0; i < menu.size(); i++) {
            MenuItem item = menu.getItem(i);
            SpannableString spanString = new SpannableString(item.getTitle().toString());
            spanString.setSpan(new ForegroundColorSpan(Color.BLACK), 0, spanString.length(), 0);
            item.setTitle(spanString);
        }
        
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.action_logout) {
            preferenceManager.clearSession();
            startActivity(LoginActivity.class);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    private void startActivity(Class<?> cls) {
        startActivity(new Intent(this, cls));
    }

    @Override
    protected void onResume() {
        super.onResume();
        
        // 如果定位服务已停止，重新启动
        if (!isLocationServiceRunning && locationManager != null) {
            locationManager.requestLocationUpdates(locationRequest, this);
            isLocationServiceRunning = true;
        }
        
        // 恢复地图
        if (mapView != null) {
            mapView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        
        // 暂停地图
        if (mapView != null) {
            mapView.onPause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 应用进入后台时不停止定位服务，保持后台定位
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        
        // 停止定位服务
        if (locationManager != null) {
            locationManager.removeUpdates(this);
            isLocationServiceRunning = false;
        }
        
        // 销毁地图
        if (mapView != null) {
            mapView.onDestroy();
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        // MapView没有参数版本的onSaveInstanceState方法
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mapView != null) {
            mapView.onStart();
        }
    }
} 